package org.hpin.common.util;

import java.io.FileOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class XmlUtils {

	private static final Logger logger = LoggerFactory.getLogger(XmlUtils.class);
	/**
	 * 读配置文件转换为map
	 * @param xmlPath
	 * @return
	 */
	public static Map<String,String> readXml2Map(String xmlPath){
		Document document = XmlDom4j.loadXML(xmlPath);
		Element root = document.getRootElement();
		List<Element> resultElement = root.elements();//值结点
		Map<String,String> keyValue = new HashMap<String,String>();
		for(Element e:resultElement){
			String nodeName = e.getName();
			String method = e.attributeValue("method");
			keyValue.put(nodeName, method);
		}
		return keyValue;
	}
	
	/**
	 * 改变xml文件中的日期
	 * @param xmlPath
	 * @param now
	 */
	public static void changDate(String xmlPath,String now,String xmlCode){
		
		logger.info("XmlUtils中，changeDate传递进来的xmlPath是：" + xmlPath) ;
	    Document document = XmlDom4j.loadXML(xmlPath);
		System.out.println("start xml date........................................................");
		Element root = document.getRootElement();
		System.out.println("xml加载根节点：" + root.getName()) ;
		System.out.println("start xml date root........................................................");
		System.out.println("*********************************分隔符*************************************") ;
		System.out.println("*********************************分隔符*************************************") ;
		try{
			System.out.println("第一层:::::::::::::" + root.element("MsgData").getName()) ;
		}catch(Exception e){
			logger.error("读取<MsgData>节点失败！==============================") ;
		}
		
		Element resultElement = root.element("MsgData").element("Transaction").element(xmlCode).element("HL_DATE");
		System.out.println("start xml date resultElement........................................................");
		resultElement.setText(now);
		XMLWriter writer;
		try {
			writer = new XMLWriter(new FileOutputStream(xmlPath));
			writer.write(document);
			System.out.println("start xml write document date........................................................");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 类型转换
	 * @param type
	 * @return
	 */
	public static Class parseType(String type){
		Class aa = null;
		if(StringUtils.isNotBlank(type)){
			if("String".equals(type)){
				aa =  String.class;
			}
			if("Integer".equals(type)){
				aa =  Integer.class;
			}
			if("Double".equals(type)){
				aa =  Double.class;
			}
			if("Date".equals(type)){
				aa =  Date.class;
			}
			if("Long".equals(type)){
				aa = Long.class;
			}
		}
		return aa;
	}
	
	/**
	 * 解析xml为对象
	 * @param dataXmlPath
	 * @param fieldXmlPath
	 * @param entity
	 * @param dataRoot
	 */
	public static List<Object> parseXml2Object(String dataXmlPath,String fieldXmlPath,Class a,String dataRoot){
		List<Object> entityList = new ArrayList<Object>();
		logger.info("XmlUtils中，parseXml2Object传递进来的xmlPath是：" + dataXmlPath) ;
		Document document = XmlDom4j.loadXML(dataXmlPath);
		Element root = document.getRootElement();
		Element msgElement = root.element("MsgData"); //获得MsgData结点
		List<Element> traElementList = msgElement.elements("Transaction");
		for(Element traElement:traElementList){
			Element hlElement = traElement.element(dataRoot);
			Object entity = null;
			try {
				entity = a.newInstance();
				//读配置文件
				Map<String,String> fieldMap = readXml2Map(fieldXmlPath);
				Set<String> field = fieldMap.keySet();
				Iterator<String> it = field.iterator();
				System.out.println("field值是："+fieldMap.size());
				while(it.hasNext()){
					String fieldName =  it.next();//字段名称
					System.out.println("===="+fieldName);
					Element e = hlElement.element(fieldName);
					Object value = e.getTextTrim(); 
					if(StringUtils.isBlank(value.toString())){
						continue;
					}
					String type = fieldMap.get(fieldName).split("_")[0];
					String method = fieldMap.get(fieldName).split("_")[1];
					System.out.println("tpye===="+type+" method=="+method);
					value = ReflectionUtils.convertStringToObject(value, parseType(type));
					System.out.println("value======"+value);
					//反射调用方法
					a.getMethod(method,new Class[]{parseType(type)}).invoke(entity, new Object[]{value});
					System.out.println(fieldName+"的值是："+value);
				}
			} catch (Exception e1) {
				e1.printStackTrace();
				System.out.println("出错信息：======================== " + e1.getMessage()) ;
				logger.error("XmlUtils --------> 出错啦！");
			}
			entityList.add(entity);
		}
		return entityList;
	}
	
	
	public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
		String dataPath1 = "/resources/config/dept/deptOutput.xml";
		String xmlPath1 = "/resources/config/dept/deptField.xml";
		//String xmlPath2 = "config/deptOutput.xml";
		//String desPath2 = "config/deptField.xml";
		//人办资源中的用户
		/**
		List<Object> aaaList = parseXml2Object(xmlPath1,dataPath1,PersonData.class);
		for(Object aaa:aaaList){
			PersonData cc = (PersonData)aaa;
			User user = new User();
			PropertyUtils.copyProperties(user,cc);
			System.out.println(user.getEmplid());
			System.out.println(cc.getEmailAddr());
		}**/
		//人办资源中的部门
//		List<Object> bbbList =  parseXml2Object(dataPath1,xmlPath1,Dept.class,"HL_DEPT_RES");
//		for(Object bbb:bbbList){
//			Dept dd = (Dept)bbb;
//			Dept org = new Dept();
//			PropertyUtils.copyProperties(org,dd);
//			//System.out.println(org.getDescrshort());
//			System.out.println(dd.getDescrshort());
//		}
	}
}
